package com.da.javatest.interview.session2;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

/**
 * @author chenlida
 * @date 2020/4/4 17:34
 *
 * 强引用：即使发生OOM也不会被回收
 * 软引用：内存不足才回收
 * 弱引用：只要GC就会回收
 * 虚引用：在任何时候都能被回收
 *
 * 引用队列：get对象永远为null,GC前如果有finalize(),GC之后对象会进入引用队列
 */
public class Test25Reference {
    public static void main(String[] args) {
        // strongReference();
        // softReference();
        // weakReference();
        // weakHashMap();
        referenceQueue();
    }

    private static void referenceQueue() {
        Object o = new Object();
        ReferenceQueue<Object> rq = new ReferenceQueue<>();
        WeakReference<Object> wr = new WeakReference<>(o, rq);
        System.out.println(o);
        System.out.println(wr.get());
        System.out.println(rq.poll());

        System.out.println("========================");
        o = null;
        System.gc();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(o);
        System.out.println(wr.get());
        System.out.println(rq.poll());
    }

    private static void weakHashMap() {
        WeakHashMap<String, String> weakHashMap = new WeakHashMap<>();
        //String key = "key";
        String key = new String("key");
        String value = "value";
        weakHashMap.put(key, value);
        System.out.println(weakHashMap);
        key = null;
        System.gc();
        System.out.println(weakHashMap);
    }

    private static void weakReference() {
        Object o1 = new Object();
        WeakReference<Object> wr = new WeakReference<>(new Object());

        System.gc();
        System.out.println(o1);
        System.out.println(wr.get());
    }

    private static void softReference() {
        //-Xms10m -Xmx10m
        Object o1 = new Object();
        SoftReference sr = new SoftReference<>(new Object());

        System.gc();
        try {
            byte[] bytes = new byte[10 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(o1);
            System.out.println(sr.get());
        }
    }

    private static void strongReference() {
        Object o1 = new Object();
        Object o2 = o1;
        o1 = null;

        System.gc();
        System.out.println(o1);
        System.out.println(o2);
    }
}
